package com.cry.core.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cry.todo.dao.UserDao;
import com.cry.todo.domain.User;

@Repository
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDao<User> userDao;
	
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

    	UserDetails userDetails = userDao.loadByUserDetails(username);

    	if(userDetails == null) throw new UsernameNotFoundException("A felhasznalo a megadott felhasznalonevvel nem talalhato: " + username);

    	return userDetails; 
    }
    
    @Override
    public User getSessionUser() {
    	UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	
    	return userDao.load(userDetails.getUserId());
    	
    }
}